package com.mall.pay.service;

import com.alipay.demo.trade.Main;
import com.alipay.demo.trade.model.TradeStatus;
import com.mall.order.OrderCoreService;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.pay.PayService;
import com.mall.pay.cache.CacheManager;
import com.mall.pay.constrant.PayRetCode;
import com.mall.pay.dto.PayRequest;
import com.mall.pay.dto.PayResponse;

import com.mall.pay.dto.QueryStatusRequest;
import com.mall.pay.dto.QueryStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lichao
 * @createdate 2021-01-27 17:21
 */
@Service
@Component
@Slf4j
public class IPayService implements PayService {

    @Autowired
    Main main;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    CacheManager cacheManager;

    @Override
    public PayResponse pay(PayRequest request) {

        PayResponse payResponse = main.test_trade_precreate(request);

        return payResponse;
    }

    @Override
    public QueryStatusResponse queryStatus(QueryStatusRequest request) {
        QueryStatusResponse response = new QueryStatusResponse();
        TradeStatus tradeStatus = main.test_trade_query(request.getOrderId());
        if(tradeStatus.equals(TradeStatus.SUCCESS)){
            response.setPayRetCode(PayRetCode.SUCCESS);
            log.info("订单支付成功");
            Integer effectedRow = orderMapper.updataOrderPayed(request.getOrderId());
            if (effectedRow == 1){
                log.info("订单支付状态修改成功");
            }else if(effectedRow == 0){
                log.error("修改订单支付状态失败");
            }else {
                log.error("修改订单支付状态时系统异常");
            }
        }else {
            response.setPayRetCode(PayRetCode.FAIL);
            log.error("订单未支付");
        }


        return response;
    }
}
